package com.bamanker.cloudconsumer.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * feign令牌中继
 * 此方法开启熔断也可以拿到token
 *
 * @author bamanker
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    private static final Pattern BEARER_TOKEN_HEADER_PATTERN = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+=*)$",

            Pattern.CASE_INSENSITIVE);

    @Override
    public void apply(RequestTemplate requestTemplate) {


        final String authorization = HttpHeaders.AUTHORIZATION;

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (Objects.nonNull(requestAttributes)) {

            String authorizationHeader = requestAttributes.getRequest().getHeader(HttpHeaders.AUTHORIZATION);

            Matcher matcher = BEARER_TOKEN_HEADER_PATTERN.matcher(authorizationHeader);

            if (matcher.matches()) {

                // 清除token头 避免传染

                requestTemplate.header(authorization);

                requestTemplate.header(authorization, authorizationHeader);

            }
        }
    }
}

